package org.thraex.pms.question.filter;

import lombok.extern.java.Log;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Optional;

/**
 * @Author 鬼王
 * @Date 2019/08/23 12:34
 */
@Log
public class GlobalFilter implements Filter {

    //private static final Logger log = Logger.getLogger(GlobalFilter.class.getSimpleName());

    private ServletContext servletContext;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info(">>>>>>>>>>>>>>>>>> Execute #init(FilterConfig filterConfig)");
        log.info(">>>>>>>>>>>>>>>>>> init-param name " + filterConfig.getInitParameter("name"));
        this.servletContext = filterConfig.getServletContext();
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.info(">>>>>>>>>>>>>>>>>> Execute #doFilter(ServletRequest request, ServletResponse response, FilterChain chain)");

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        log.info(">>>>>>>>>>>>>>>>>> Request servlet path: " + req.getServletPath());

        /*
        Enumeration servlets = this.servletContext.getServlets();
        while (servlets.hasMoreElements()) {
            String hn = servlets.nextElement().toString();
            System.out.println(hn);
        }
        Enumeration servletNames = this.servletContext.getServletNames();
        while (servletNames.hasMoreElements()) {
            String hn = servletNames.nextElement().toString();
            System.out.println(hn);
        }
        Servlet download = this.servletContext.getServlet("Download");
        */

        final String pn = "flag";
        if (Optional.ofNullable(req.getParameter(pn)).isPresent()) {
            ServletOutputStream os = resp.getOutputStream();
            byte[] bytes = "<h1 style='color: red;text-align: center;'>未知错误</h1>".getBytes(Charset.forName("UTF-8"));
            log.info(">>>>>>>>>>>>>>>>>> Output byte size: " + bytes.length);

            resp.setContentType("text/html;charset=UTF-8");
            resp.setContentLength(bytes.length);
            os.write(bytes);
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
        log.info(">>>>>>>>>>>>>>>>>> Execute #destroy()");
    }

}
